package com.nageoffer.shortlink.admin.config;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nageoffer.shortlink.admin.common.convention.result.Result;
import com.nageoffer.shortlink.admin.dao.entity.UserContext;
import com.nageoffer.shortlink.admin.dao.entity.UserDO;
import com.nageoffer.shortlink.admin.dao.mapper.UserMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private StringRedisTemplate redisTemplate;
    
    @Resource
    private UserMapper userMapper;

    @Resource
    private ObjectMapper objectMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        // 1. 获取session
        HttpSession session = request.getSession(false);
        if (session == null) {
            response.setStatus(200);
            Result<Void> result = new Result<>();
            result.setCode("401");
            result.setMessage("未登录");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        // 2. 检查session是否在黑名单中（已登出）
        String sessionId = session.getId();
        if (redisTemplate.hasKey("session:blacklist:" + sessionId)) {
            response.setStatus(200);
            Result<Void> result = new Result<>();
            result.setCode("401");
            result.setMessage("会话已过期或已登出");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        // 3. 从session中获取用户名，查询用户信息
        String username = (String) session.getAttribute("username");
        if (username == null) {
            response.setStatus(200);
            Result<Void> result = new Result<>();
            result.setCode("401");
            result.setMessage("会话无效");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }

        UserDO userDO = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, username));
        if (userDO == null) {
            response.setStatus(200);
            Result<Void> result = new Result<>();
            result.setCode("401");
            result.setMessage("用户不存在");
            response.getWriter().write(objectMapper.writeValueAsString(result));
            return false;
        }
        // 4. 将用户信息存入ThreadLocal
        UserContext.setUser(userDO);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.clear();
    }
}